﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taurus.Platform.DTO;
using Taurus.Parking.DTO;
using HtmlAgilityPack;
using Taurus.Platform.Net;
using Newtonsoft.Json.Linq;
using MSScriptControl;

namespace Taurus.Parking.BLL
{
    class MyGarage
    {
        #region field

        private const string MY_GARAGE_URL = @"http://www.kaixin001.com/!parking/index.php";
        private const string OTHER_PARK_URL = "http://www.kaixin001.com/!parking/!user.php?puid={0}&verify={1}";
        private const string PARK_URL = "http://www.kaixin001.com/!parking/!park.php?verify={0}&park_uid={1}&parkid={2}&carid={3}&neighbor={5}&acc={4}&first_fee_parking=0";

        private const string STICKER_URL = "http://www.kaixin001.com/!parking/!post.php?verify={0}&parkid={1}&acc={2}";

        private const string NEIGHBOR_URL = "http://www.kaixin001.com/!parking/!neighbor.php?verify={0}&puid={1}";

        private string _verify;//验证字段
        private string _acc;//暗错错额字段

        private HtmlDocument _cacheDoc;
        private ParkingUser _myAccount; //我的账号
        private List<string> _friendsUID;//可停车的好友账号

        #endregion

        #region property

        public string Name { get { return _myAccount.Name; } }

        public ParkingUser MyAccount { get { return _myAccount; } }

        #endregion

        #region Construction

        public MyGarage(ParkingUser account)
        {
            _myAccount = account;
            _cacheDoc = Util.AccessPage(_myAccount, MY_GARAGE_URL);
            _friendsUID = new List<string>();

            InitMyData();
        }

        #endregion

        #region private

        private void InitMyData()
        {
            string html = _cacheDoc.DocumentNode.InnerHtml;
            int s = html.IndexOf("g_verify") + 12;
            int e = html.Substring(s).IndexOf(";");
            _verify = html.Substring(s, e - 1);

            string script = html.Substring(s - 1, html.IndexOf("</script>", s) - s);
            ScriptControlClass sc = new ScriptControlClass();
            sc.Language = "javascript";
            sc.AddCode(script);
            object[] p = new object[] { null };
            _acc = sc.Run("acc", ref p).ToString();

            s = html.IndexOf("v_userdata") + 13;
            e = html.IndexOf(";", s);
            string v_userdata = html.Substring(s, e - s);

            html = html.Substring(e + 1);
            s = html.IndexOf("[");
            e = html.IndexOf(";");
            string v_frienddata = html.Substring(s, e - s);

            JArray jfrienddata = JArray.Parse(v_frienddata);
            var id = from uid in jfrienddata where uid["full"].Value<int>() == 0 orderby uid["scenemoney"].Value<string>() descending select (string)uid["uid"];
            _friendsUID = id.ToList();

            InitData(v_userdata, _myAccount);
        }

        private void InitData(string json, ParkingUser user)
        {
            JObject juserdata = JObject.Parse(json);//用户数据
            user.Cash = juserdata["user"]["cash"].Value<string>();
            user.Name = (string)juserdata["user"]["real_name"];

            Garage garage = new Garage();
            garage.Scene = (string)juserdata["user"]["avenue"];
            garage.MoneyMinute = juserdata["config"]["money_minute"].Value<string>();

            if (juserdata["car"] != null)
            {
                var cars = from item in juserdata["car"]
                           select new Car()
                           {
                               ID = item["carid"].Value<int>(),
                               Price = (string)item["price"],
                               Name = (string)item["car_name"],
                               PicFullPath = (string)item["car_logo_big"],
                               Park = new Park()
                               {
                                   ID = item["parkid"].Value<string>(),
                                   OwnerName = (string)item["park_real_name"],
                                   Profit = (int)item["park_profit"]
                               }
                           };
                garage.MyCars = cars.ToList();
            }

            var parks = from item in juserdata["parking"]
                        select new Park()
                        {
                            ID = (string)item["parkid"],
                            Profit = (int)item["car_profit"],
                            Car = new Car()
                            {
                                ID = item["carid"].Value<int>(),
                                Price = (string)item["car_price"],
                                Name = (string)item["car_name"],
                                OwnerName = (string)item["car_real_name"],
                                PicFullPath = (string)item["car_logo_big"]
                            }
                        };
            garage.MyParks = parks.ToList();

            user.Garage = garage;
        }

        private void InitNeighborData(ParkingUser account)
        {
            //获取account数据            
            HtmlAgilityPack.HtmlDocument doc = Util.AccessPage(_myAccount, string.Format(NEIGHBOR_URL, _verify, account.UID));
            InitData(doc.DocumentNode.InnerText, account);
        }

        #endregion

        #region methods
        /// <summary>
        /// 更新数据
        /// </summary>
        public void UpdateMyData()
        {
            _cacheDoc = Util.AccessPage(_myAccount, MY_GARAGE_URL);
            InitMyData();
        }

        /// <summary>
        /// 根据account初始化数据
        /// account的汽车属性不被复制
        /// </summary>
        /// <param name="account"></param>
        public void InitUserAccountData(ParkingUser account)
        {
            //获取account数据            
            HtmlAgilityPack.HtmlDocument doc = Util.AccessPage(_myAccount, string.Format(OTHER_PARK_URL, account.UID, _verify));
            InitData(doc.DocumentNode.InnerText, account);
        }
        

        /// <summary>
        /// 购买新车
        /// </summary>
        /// <param name="car"></param>
        public void BuyCar(Car car)
        {
            //TODO:购买新车
        }
        /// <summary>
        /// 出售车辆
        /// </summary>
        /// <param name="car"></param>
        public void SellCar(Car car)
        {
            //TODO:出售车辆
        }
        /// <summary>
        /// 停车
        /// </summary>
        /// <param name="uid">停在谁的车库</param>
        /// <param name="carid">被停车辆ID</param>
        private JObject Parking(string uid, string carid)
        {
            ParkingUser who = new ParkingUser();
            who.UID = uid;
            if (who.IsNeighbor)
            {
                //邻居
                InitNeighborData(who);
            }
            else
            {
                InitUserAccountData(who);
            }
            if (!who.IsFull())
            {
                foreach (var park in who.Garage.MyParks)
                {
                    if (park.Car.ID == 0)
                    {
                        HtmlDocument doc = Util.AccessPage(_myAccount, string.Format(PARK_URL, _verify, who.UID, park.ID, carid, _acc, who.IsNeighbor ? 1 : 0), "post");
                        return JObject.Parse(doc.DocumentNode.InnerText);
                    }
                }
            }
            return null;
        }
        public JObject Parking(string carid)
        {
            foreach (var uid in _myAccount.PriorityUsers)
            {
                JObject jo = Parking(uid, carid);
                if (jo == null)
                    continue;//车位停满了
                else
                {
                    int errno = (int)jo["errno"];
                    if (errno == 0)
                    {
                        return jo;
                    }
                }

            }
            foreach (var uid in _friendsUID)
            {
                if (!_myAccount.PriorityUsers.Contains(uid))
                {
                    JObject jo = Parking(uid, carid);
                    if (jo == null)
                        continue;//车位停满了
                    else
                    {
                        int errno = (int)jo["errno"];
                        if (errno == 0)
                        {
                            return jo;
                        }
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 贴条
        /// </summary>
        /// <param name="parkid"></param>
        /// <returns></returns>
        public JObject Sticker(string parkid)
        {
            HtmlDocument doc = Util.AccessPage(_myAccount, string.Format(STICKER_URL, _verify, parkid, _acc), "post");
            return JObject.Parse(doc.DocumentNode.InnerText);
        }
        #endregion

    }
}
